const WORK_TIME = 25 * 60;
const REST_TIME = 5 * 60;
const LONG_REST_TIME = 30 * 60;
const LOOP_COUNT = 4;

// const WORK_TIME = 5;
// const REST_TIME = 3;
// const LONG_REST_TIME = 7;

const timerContainer = document.querySelector(".timer-container");
const dialogEl = document.querySelector("#action");

const dialogBtn = document.querySelector(".btn-container");
const workBtn = document.querySelector(".work_btn");
const restBtn = document.querySelector(".rest_btn");
workBtn.addEventListener("click", () => {
    dialogEl.close();
    startCountdown("work");
});
restBtn.addEventListener("click", () => {
    // 弹窗询问窗口时，如果鼠标没移出窗口，就会出现重置按钮，因此点击休息按钮就隐藏它
    if (!restBtn.classList.contains("reset_btn__hidden")) mouseleaveCallback();
    dialogEl.close();
    startCountdown("rest");
});

// 将毫秒转换为秒
function formatMS(ms) {
    const totalSeconds = ms / 1000;

    const minutes = Math.floor(totalSeconds / 60);
    const seconds = Math.floor(totalSeconds % 60);

    const formattedMinutes = String(minutes).padStart(2, "0");
    const formattedSeconds = String(seconds).padStart(2, "0");

    return `${formattedMinutes}:${formattedSeconds}`;
}

// 更新 ui 界面
const updateTime = ms => {
    // timerContainer.innerText = formatMS(ms);
    bar.setText(formatMS(ms));
};

const showInteractiveDialog = () => {
    removeResetBtn();
    dialogEl.showModal();
};

// 计时开始
let timer;
let currentLoop = 0;
const startCountdown = signal => {
    timerContainer.style.display = "none";

    let time = signal === "rest" ? REST_TIME : WORK_TIME;
    if (signal === "work") currentLoop++;
    if (signal === "rest" && currentLoop >= LOOP_COUNT) {
        time = LONG_REST_TIME;
        currentLoop = 0;
    }

    if (timer) timer.stop();
    timer = new Timer({
        ontick: ms => updateTime(ms),
        onend: () => notification(signal, currentLoop)
    });

    timer.start(time);
    setProgressBar(time);
    showResetBtn(signal);
};

// 计时结束，通知时间到
const notification = async (signal, countLoop) => {
    const res = await window.electronAPI.timeUp(signal, countLoop);

    switch (res) {
        case "rest":
            alert("该休息啦！");
            break;
        case "work":
            startCountdown("work");
            break;
        default:
            showInteractiveDialog();
            break;
    }
};

// 开始按钮
const startBtn = document.querySelector(".start_btn");
startBtn.addEventListener("click", () => {
    startCountdown("work");
    startBtn.style.display = "none";
});

// 重置按钮
const resetBtn = document.querySelector(".reset_btn");

resetBtn.addEventListener("click", () => {
    startCountdown("work");
});

const mouseenterCallback = () => {
    resetBtn.classList.remove("reset_btn__hidden");
    const displayValue = window.getComputedStyle(startBtn).display;
    if (displayValue === "none") resetBtn.classList.add("reset_btn__show");
};
const mouseleaveCallback = () => {
    resetBtn.classList.remove("reset_btn__show");
    resetBtn.classList.add("reset_btn__hidden");
};
const showResetBtn = signal => {
    if (signal !== "work") return;
    document.body.addEventListener("mouseenter", mouseenterCallback);
    document.body.addEventListener("mouseleave", mouseleaveCallback);
};

const removeResetBtn = () => {
    document.body.removeEventListener("mouseenter", mouseenterCallback);
    document.body.removeEventListener("mouseleave", mouseleaveCallback);
};

// 计时圆环
const progressBarEl = document.querySelector(".progress-bar");
let bar;
const setProgressBar = duration => {
    if (bar) bar.destroy();
    bar = new ProgressBar.Circle(progressBarEl, {
        color: "salmon",
        strokeWidth: 5, // 正好是从圆心开始画起，>50会越过圆心，<50画出的是圆环
        trailWidth: 0, // 也设置为50，就是一个未填充的圆形，而不是圆环。要么设置为0
        easing: "linear",
        duration: duration * 1000,
        // duration: 5000,
        text: {
            style: {
                color: "yellow",
                display: "inline-block",
                position: "absolute",
                top: "50%",
                left: "50%",
                fontSize: "3rem",
                fontWeight: "bold",
                transform: "translate(-50%,-50%)"
            },
            autoStyleContainer: true
        },
        // fill: 'salmon',   // 圆形内容区域填充色，当需要画圆环时，效果应该最好。
        from: { color: "#ed8383" },
        to: { color: "#ffffff" },
        step: function (state, circle) {
            // 进度条随进度颜色渐变
            circle.path.setAttribute("stroke", state.color);
            // 进度百分比文字
            // const value = Math.round(circle.value() * 100);
            // circle.setText(value + "%");
        }
    });
    // bar.text.style.fontFamily = '"Raleway", Helvetica, sans-serif';
    // bar.text.style.fontSize = "2rem";

    bar.animate(1.0, function () {
        // console.log("动画执行结束");
    });
};
